from AIManager import AIManager
from DataAnalysisAssistant import DataAnalysisAssistant
from ImageGenerationAssistant import ImageGenerationAssistant
from TextGenerationAssistant import TextGenerationAssistant
from TranslationAssistant import TranslationAssistant
from VoiceAssistant import VoiceAssistant


class Main:
    """主程序类"""
    def __init__(self):
        self.ai_manager = AIManager(20)  # 初始化管理器（最大容量20）

    def show_menu(self) -> None:
        """显示菜单"""
        print("\n========== 🤖AI助手管理器 ==========")
        print("1. 查看所有AI助手列表")
        print("2. 根据ID查询助手详情")
        print("3. 添加新的AI助手")
        print("4. 根据ID修改助手信息")
        print("5. 删除AI助手（按ID）")
        print("6. 启动AI助手服务")
        print("7. 停止AI助手服务")
        print("8. 为AI助手分配任务")
        print("9. 显示系统统计信息")
        print("0. 退出系统")
        print("===================================")

    def get_valid_choice(self) -> int:
        """获取有效的用户选择"""
        while True:
            try:
                choice = input("请选择操作: ").strip()
                return int(choice)
            except ValueError:
                print("输入无效，请输入0-9之间的数字：", end="")

    def get_valid_type_choice(self) -> int:
        """获取有效的类型选择"""
        while True:
            try:
                choice = input("输入无效，请选择1-5之间的类型：").strip()
                choice_int = int(choice)
                if 1 <= choice_int <= 5:
                    return choice_int
            except ValueError:
                pass

    def show_all_assistants(self) -> None:
        """显示所有助手"""
        assistants = self.ai_manager.get_all_assistants()
        if not assistants:
            print("ℹ️ 当前无AI助手数据")
            return

        print("所有AI助手列表：")
        for i, assistant in enumerate(assistants, 1):
            print(f"{i}. {assistant}")

    def query_assistant_by_id(self) -> None:
        """根据ID查询助手"""
        aid = input("请输入要查询的AI助手ID: ").strip()
        assistant = self.ai_manager.find_assistant_by_id(aid)
        if assistant is None:
            print(f"❌ 未找到ID为{aid}的助手")
        else:
            print(f"✅ 查询结果: {assistant}")

    def add_new_assistant(self) -> None:
        """添加新助手"""
        print("添加新AI助手")
        aid = input("请输入ID: ").strip()
        name = input("请输入名称: ").strip()
        version = input("请输入版本号: ").strip()

        # 处理在线状态
        is_online_input = input("是否在线？(1-是, 0-否): ").strip()
        is_online = is_online_input == "1"

        # 处理能力评分
        try:
            score_input = input("请输入能力评分(0-100): ").strip()
            score = int(score_input)
            if not (0 <= score <= 100):
                print("❌ 评分无效（需0-100），添加失败！")
                return
        except ValueError:
            print("❌ 评分需为数字，添加失败！")
            return

        # 处理助手类型
        print("请选择助手类型（1-数据分析 2-图片生成 3-文本生成 4-翻译 5-语音）: ", end="")
        type_choice = self.get_valid_type_choice()
        new_assistant = None

        if type_choice == 1:
            data_formats = input("请输入支持的数据格式（如CSV,Excel）: ").strip()
            new_assistant = DataAnalysisAssistant(aid, name, version, is_online, score, data_formats)
        elif type_choice == 2:
            resolution = input("请输入最大支持分辨率（如4K,8K）: ").strip()
            new_assistant = ImageGenerationAssistant(aid, name, version, is_online, score, resolution)
        elif type_choice == 3:
            text_types = input("请输入支持的文本类型（如诗歌,文案）: ").strip()
            new_assistant = TextGenerationAssistant(aid, name, version, is_online, score, text_types)
        elif type_choice == 4:
            languages = input("请输入支持的翻译语言对（如中英,中日）: ").strip()
            new_assistant = TranslationAssistant(aid, name, version, is_online, score, languages)
        elif type_choice == 5:
            voice_langs = input("请输入支持的语音语言（如中文,英文）: ").strip()
            new_assistant = VoiceAssistant(aid, name, version, is_online, score, voice_langs)

        if new_assistant:
            print(self.ai_manager.add_assistant(new_assistant))

    def update_assistant_info(self) -> None:
        """更新助手信息"""
        print("修改AI助手数据")
        aid = input("请输入ID: ").strip()
        input_str = input(
            "可修改属性列表为：name,type,version,online,score\n请输入要修改的属性和值（用空格分割）: ").strip()
        parts = input_str.split(" ", 1)

        if len(parts) < 2:
            print("❌ 输入格式错误，需为\"属性 值\"（如：score 100）")
            return

        property_, value = parts
        print(self.ai_manager.update_assistant(aid, property_, value))

    def delete_assistant_by_id(self) -> None:
        """删除助手"""
        aid = input("请输入要删除的AI助手ID: ").strip()
        print(self.ai_manager.delete_assistant(aid))

    def start_assistant_service(self) -> None:
        """启动助手服务"""
        aid = input("请输入要启动的AI助手ID: ").strip()
        print(self.ai_manager.start_assistant(aid))

    def stop_assistant_service(self) -> None:
        """停止助手服务"""
        aid = input("请输入要停止的AI助手ID: ").strip()
        print(self.ai_manager.stop_assistant(aid))

    def assign_task_to_assistant(self) -> None:
        """分配任务给助手"""
        aid = input("请输入目标AI助手ID: ").strip()
        task = input("请输入任务内容: ").strip()
        print(self.ai_manager.assign_task(aid, task))

    def show_statistics(self) -> None:
        """显示统计信息"""
        print(self.ai_manager.get_statistics())

    def run(self) -> None:
        """运行主程序"""
        print("欢迎使用 AI助手管理器 v1.0")
        while True:
            self.show_menu()
            choice = self.get_valid_choice()
            if choice == 0:
                print("感谢使用，再见！")
                break

            # 处理用户选择
            if choice == 1:
                self.show_all_assistants()
            elif choice == 2:
                self.query_assistant_by_id()
            elif choice == 3:
                self.add_new_assistant()
            elif choice == 4:
                self.update_assistant_info()
            elif choice == 5:
                self.delete_assistant_by_id()
            elif choice == 6:
                self.start_assistant_service()
            elif choice == 7:
                self.stop_assistant_service()
            elif choice == 8:
                self.assign_task_to_assistant()
            elif choice == 9:
                self.show_statistics()
            else:
                print("❌ 无效操作，请重新选择！")


if __name__ == "__main__":
    main = Main()
    main.run()